//
//  BookstoreViewModel.swift
//  SLQuickReader
//
//  Created by ALin on 2017/8/3.
//  Copyright © 2017年 ALin. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift

let cellMargin: CGFloat = 3.0

class BookstoreViewModel: BaseViewModel, BaseView{
    
    var cellHeights: [CGFloat] = []
    private weak var tableView: UITableView!
    
    
    fileprivate func bind2fetchStatistics(){
        
        // ② 然后再请求网络数据
        let statisticsObserver = BookstoreProvider
                                    .request(.statistics)
                                    .parseStatistics()
                                    .catchError{error in
                                            return self.loadLocalStatistics()?.parseLocalStatistics() ?? Observable<[[String: [Statistics]]]>.just([])
                                        }
        delStatistics(observer: statisticsObserver)
    }
    
    
    func bind(to view: UIView...) {
        if view.first is UITableView {
            tableView = (view.first as! UITableView)
            bind2fetchStatistics()
            tableView.rx.setDelegate(self).disposed(by: disposBag)
        }
    }
    
    fileprivate func loadLocalStatistics() -> Observable<Data>?{
        guard let data = UserDefaults.standard.value(forKey: "statistics") as? Data else {
            return nil
        }
        return Observable.just(data)
    }
    
    fileprivate func delStatistics(observer: Observable<[[String: [Statistics]]]>){
        observer
            .subscribe(onNext: { [weak self] list in
            self?.cellHeights.removeAll()
            for item in list{
                let count: Int = item.values.first!.count
                let rows: Int = (count % 3 == 0) ? (count / 3) : (count / 3 + 1)
                let height = StatisticsCellHeight + StatisticsBtnHeight * CGFloat(rows) + cellMargin
                self?.cellHeights.append(CGFloat(height))
                self?.tableView.reloadData()
            }
            }, onError: { (error) in
                print(error)
        }).disposed(by: disposBag)
        // 这儿必须先设置dataSource为nil
        // 因为如果是先从本地拿了数据, tableview就会绑定好了DataSource. 然后我们再从服务器拿到数据, 此时就会重复设置DataSource, 就会报错
//        tableView.dataSource = nil
        observer.bind(to: tableView
            .rx
            .items(cellIdentifier: "cell", cellType: StatisticsCell.self)){ row, element, cell in
                let model = StatisticsViewModel()
                model.statistics = element
                model.bind(to: cell)
            }.disposed(by: disposBag)

    }
}

extension BookstoreViewModel: UITableViewDelegate{
    /// UITableViewDelegate
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row < cellHeights.count {
             return cellHeights[indexPath.row]
        }
        return 44
    }
}
